//index.js
const Controllers = require('../../controllers/Controller.js').controller;
const controller = require("../../controllers/Controller").controller
const utils = require('../../../utils/util.js');
const app = getApp();

Page({
  data: {
    // formData: {
    //   grade: '',
    //   name: '',
    //   userName: '',
    //   phone: '',
    //   address: []
    // },
    types: [
      { name: 'B', value: 1, status: 0 },
      { name: 'C', value: 2, status: 1 }
    ],
    // formData: {
    //   type: 0,
    //   agentName: '门店名称',
    //   adminName: '负责人',
    //   mobile: '13700000000',
    //   rovinceName: '广东省',
    //   cityName: '广州市',
    //   districtName: '天河区',
    //   idImg: 'http://111.230.226.223/upload/account/20201017/767036170763763712.png',
    //   idBackImg: 'http://111.230.226.223/upload/account/20201017/767036204100091904.png',
    //   // agentImg: 'http://111.230.226.223/upload/account/20201017/767036170763763712.png',
    //   internalImgs: '',
    //   internalImgArr: [
    //     'http://111.230.226.223/upload/account/20201017/767052763245838336.png',
    //     'http://111.230.226.223/upload/account/20201017/767054095545532416.png',
    //     'http://111.230.226.223/upload/account/20201017/767057376372064256.png'
    //   ]
    // },
    formData: {},
    internalImgArr: [],
    IDData: [
      {
        text: '正面',
        img: '',
        type: 'idImg',
        status: 1
      },
      {
        text: '正面示例图',
        img: '',
        // img: '../../../assets/images/home/my_picture_02@2x.png',
        status: 0
      },
      {
        text: '反面',
        img: '',
        type: 'idBackImg',
        status: 2
      },
      {
        text: '反面示例图',
        img: '',
        // img: '../../../assets/images/home/my_picture_03@2x.png',
        status: 0
      },
    ],
    agentIndexData: {},
    saving: false,
    areaListPicker: []
  },
  onLoad(option) {
    console.log('option', option);
    
    var that = this;
    that.setData({
      status: parseInt(option.status)
    })
  },
  onShow() {
    this.getAreaList()
    var that = this;
    const agentIndexData = app.globalData.agentIndexData;
    console.log('add--agentIndexData==', agentIndexData);
    var types = that.data.types;
    if (agentIndexData && agentIndexData.type === 0) {
      types[0].status = 1;
      types[1].status = 1;
    }
    that.AreaList();

    that.setData({
      types,
      agentIndexData,
      saving: false
    })
  },
  // 获取地址列表；
  AreaList() {
    var that = this;
    var agentIndexData = app.globalData.agentIndexData;
    const type = agentIndexData.type;
    const rovinceName = agentIndexData.rovinceName;
    const cityName = agentIndexData.cityName || '';
    wx.showLoading()
    // 获取省级地址
    Controllers.AreaList({leveltype: 1}).then(res => {
      console.log('AreaList--rovinceName==', rovinceName);
      console.log('AreaList----res==', res);
      const { code, data, desc } = res;
      const selRovince = data.find(d => d.name === rovinceName);
      console.log('selRovince===', selRovince);
      
        that.setData({
          rovinceList: data,
          selRovince
        })
    }).then(() => {
      // 获取市级地址；
      Controllers.AreaList({leveltype: 2}).then(res => {
        console.log('AreaList--2--res==', res);
        const { code, data, desc } = res;
        var selCity = '';
        if (type === 1) {
          selCity = data.find(d => d.name === cityName);
        }
        that.setData({
          cityList: data,
          selCity
        })
      }).then(() => {
        // B级代理商才需要获取 区级地址
        Controllers.AreaList({leveltype: 3}).then(res => {
          console.log('AreaList--3--res==', res);
          const { code, data, desc } = res;
          that.setData({
            districtList: data
          })
          that.arrangeArea(2);
          wx.hideLoading()
        })
      })
    })
  },


  columnChange(e) {
    let column = e.detail.column; //列
    let value = e.detail.value; //行

    let id = this.data.list[column][value].id;
    if (column == 0) {
      this.setData({
        shen: this.data.list[column][value].name
      })
      this.getAreaListChildShi(id);
    } else if (column == 1) {
      this.setData({
        shi: this.data.list[column][value].name
      })
      this.getAreaListChildQu(id);
    } else {
      this.setData({
        qu: this.data.list[column][value].name,
        quId: this.data.list[column][value].id
      })
    }
  },

  //获取省
  getAreaList() {
    controller.areaList({
      leveltype: 1
    }).then(res => {
      let shen = res.data;
      let id = 0;
      let shenList = "list[" + id + "]"
      this.setData({
        [shenList]: shen,
        shen: shen[0].name
      })
      this.getAreaListChildShi(res.data[0].id)
    })
  },

  //根据上层id获取市
  getAreaListChildShi(id) {
    controller.areaListChild({
      areaId: id
    }).then(res => {
      let shi = res.data;
      let id = 1;
      let shiList = "list[" + id + "]"
      this.setData({
        [shiList]: shi,
        shi: shi[0].name
      })
      this.getAreaListChildQu(res.data[0].id)
    })
  },

  //根据上层id获取区
  getAreaListChildQu(id) {
    controller.areaListChild({
      areaId: id
    }).then(res => {
      let qu = res.data;
      let id = 2;
      let quList = "list[" + id + "]"
      this.setData({
        [quList]: qu,
        qu: qu[0].name,
        quId: qu[0].id
      })
    })
  },


  change(e) {
    var formData = this.data.formData;
    formData.rovinceName = this.data.shen;
    formData.cityName = this.data.shi;
    formData.districtName = this.data.qu;
    formData.districtId = this.data.quId
    this.setData({
      formData
    })
    console.log(this.data.value);
  },


  arrangeArea(type) {
    var that = this;
    const formData = that.data.formData;
    const rovinceList = that.data.rovinceList;
    const cityList = that.data.cityList;
    const districtList = that.data.districtList;
    const selRovince = that.data.selRovince;
    const selCity = that.data.selCity;

    var selRovinceIndex = 0;
    var selCityIndex = 0;
    var selDistrictIndex = 0;

    var areaList = [[selRovince.name], []];
    var areaObj = [];
    var areaList2 = [];

    // if (type === 1) {
    //   cityList.forEach(d => {
    //     if (d.parentid === selRovince.id) {
    //       areaList[1].push(d.name);
    //     }
    //   })
    // } else if (type === 2) {
      areaList = [[], [], []];
      areaList2 = [];
      rovinceList.forEach((r, i) => {
        if (r.name === selRovince.name) {
          selRovinceIndex = i;
        }
        areaList[0].push(r.name);
        areaObj.push({
          name: r.name,
          cityLabers: [],
          childs: []
        })
        cityList.forEach((c, II)=> {
          if (II === 0) {
            areaList[1][i] = [];
            areaObj[i].childs.push([])
            // areaObj[i].childs[areaObj[i].childs.length-1] = [];
          }
          if (c.parentid === r.id) {
            // areaObj[i].childs.push({
            //   name: c.name,
            //   childs: []
            // })
            areaObj[i].cityLabers.push(c.name);
            areaObj[i].childs[areaObj[i].cityLabers.length-1] = [];

            areaList[1][i].push(c.name);
            districtList.forEach((d, III)=> {
              if (III === 0) {
                areaList[2][II] = [];
                // areaObj[i].childs[areaObj[i].childs.length-1] = [];
              }
              if (d.parentid === c.id) {
                areaObj[i].childs[areaObj[i].cityLabers.length-1].push(d.name)
                // areaObj[i].childs[areaObj[i].childs.length-1].childs.push(d.name)
                areaList[2][II].push(d.name);
              }
            })
          }
        })
      })
    // }
    console.log('arrangeArea--areaList==', areaList);
    console.log('arrangeArea--areaObj==', areaObj);
    that.setData({
      areaObj,
      selRovinceIndex,
      areaList,
      areaListPicker: formData.type === 1 ? [[selRovince.name], areaObj[selRovinceIndex].cityLabers] : [[selRovince.name], areaObj[selRovinceIndex].cityLabers, areaObj[selRovinceIndex].childs[0]]
    })
  },
  changeArea(e) {
    var that = this;
    console.log('changeArea--e==', e);
    const value = e.detail.value;
    var formData = that.data.formData;
    var areaObj = that.data.areaObj;
    var areaListPicker = that.data.areaListPicker;
    formData.rovinceName = areaListPicker[0][0];
    formData.cityName = areaListPicker[1][value[1]];
    formData.districtName = value.length >= 3 ? areaListPicker[2][value[2]] : '';
    that.setData({
      formData
    })
    console.log('changeArea--areaListPicker==', areaListPicker);
    console.log('changeArea--that.data.formData==', that.data.formData);
  },
  changeAreaColumn(e) {
    var that = this;
    console.log('changeAreaColumn--e==', e);
    const { column, value } = e.detail;
    if (column !== 1) {
      return;
    }
    var areaObj = that.data.areaObj;
    var selRovince = that.data.selRovince;
    var selRovinceIndex = that.data.selRovinceIndex;
    that.setData({
      areaListPicker: [[selRovince.name], areaObj[selRovinceIndex].cityLabers, areaObj[selRovinceIndex].childs[value]]
    })
    console.log('that.data.areaListPicker==', that.data.areaListPicker);
  },
  radioChange(e) {
    var that = this;
    console.log('radioChange--e==', e);
    var value = parseInt(e.detail.value);
    that.data.formData.type = value;
    var areaObj = that.data.areaObj;
    var selRovince = that.data.selRovince;
    var selRovinceIndex = that.data.selRovinceIndex;
    that.setData({
      formData: that.data.formData,
      areaListPicker: value === 1 ? [[selRovince.name], areaObj[selRovinceIndex].cityLabers] : [[selRovince.name], areaObj[selRovinceIndex].cityLabers, areaObj[selRovinceIndex].childs[0]]
    })
    that.AreaList();
  },
  getInput(e) {
    var that = this;
    var name = e.target.dataset.name;
    var value = e.detail.value;
    var formData = that.data.formData;
    if (name === 'phone') {
      if (value.length === 11) {
        if (!utils.checkPhone(value)) {
          wx.showToast({
            title: '手机号码格式不正确',
            icon: 'none'
          });
          return;
        } else {
          formData[name] = value;
          that.setData({
            formData
          });
        }
      }
      return;
    }
    formData[name] = value;
    that.setData({
      formData
    })
    console.log('that.data.formData==', that.data.formData);
  },
  getRegion(e) {
    var that = this;
    console.log('getRegion--e==', e);
    var value = e.detail.value;
    var formData = that.data.formData;
    // formData.address = value;
    formData.rovinceName = value[0],
    formData.cityName = value[1],
    formData.districtName = value[2],
    that.setData({
      formData
    });
  },
  closeImg(e) {
    console.log('closeImg--e==', e);
    var that = this;
    var index = e.currentTarget.dataset.index;
    var type = e.currentTarget.dataset.type;
    var internalImgArr = that.data.formData.internalImgArr || [];

    if (index > internalImgArr.length - 1) {
      return;
    }
    wx.showModal({
      title: '',
      content: '确定要删除该图片？',
      success(res) {
        if (res.confirm) {
          internalImgArr.splice(index, 1);
          that.data.formData.internalImgArr = internalImgArr;
          that.setData({
            formData: that.data.formData
          })
        }
      }
    })
  },
  uploadFile(e) {
    console.log('uploadFile--e==', e);
    var that = this;
    var status = e.currentTarget.dataset.status;
    var type = e.currentTarget.dataset.type;
    var formData = that.data.formData;
    var count = 1;
    if (!status) { return }
    if (type === 'internalImgArr') {
      count = 5;
    }
    app.uploadFile(1, img => {
      console.log('uploadFile--img==', img);
      if (type === 'internalImgArr') {
        if (!formData.internalImgArr) {
          formData.internalImgArr = [];
        }
        formData.internalImgArr.push(img);
      } else {
        formData[type] = img;
      }
      that.setData({
        formData
      })
    })
  },
  settlement(e) {
    var that = this;
    var formData = that.data.formData;
    var title = '';
    if (!formData.type) {
      title = '请选择服务商等级';
    } else if (!formData.agentName) {
      title = '请填写服务商名称';
    } else if (!formData.adminName) {
      title = '请填写负责人姓名';
    } else if (!formData.mobile) {
      title = '请填写负责人联系电话';
    } else if (!formData.idImg || !formData.idBackImg) {
      title = '请上传负责人身份证正反面';
    } else if (!formData.internalImgArr || !formData.internalImgArr.length) {
      title = '请上传合同照片';
    }
    if (!title) {
      var agentIndexData = that.data.agentIndexData;
      var rovinceName = agentIndexData.rovinceName;
      var cityName = agentIndexData.cityName;
      var districtName = agentIndexData.districtName;
      var type = agentIndexData ? agentIndexData.type : -1;
      
      if (!agentIndexData || type < 0 || that.data.saving) {
        return;
      }
      if (type === 0) {
        if (rovinceName !== formData.rovinceName) {
          title = '抱歉，不可以添加其他区域的代理商';
        }
      } else if (type === 1) {
        if (rovinceName !== formData.rovinceName || cityName !== formData.cityName) {
          title = '抱歉，不可以添加其他区域的代理商';
        }
      }
    }
    if (title) {
      wx.showToast({
        title,
        icon: 'none'
      });
      return;
    }
    
    var internalImgs = formData.internalImgArr.join(',');
    var params = { ...formData, internalImgs };
    if (formData.type === 1) {
      params.districtName = '';
    } else if (!params.districtName) {
      wx.showToast({
        title: '请重新选择代理区域',
        icon: 'none'
      })
      return
    }
    delete params.internalImgArr;
    that.data.saving = true;
    Controllers.settlement(params).then(res => {
      console.log('settlement--res==', res);
      const { code, data, desc } = res;
      wx.showToast({
        title: desc,
        icon: code === 1 ? 'success' : 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1000);
    }).catch(res => {
      that.data.saving = false;
    });
  }
})